<script setup lang="ts">
import { ref, unref, watch } from 'vue'
import {
  ElButton,
  ElTable,
  ElTableColumn,
  // ElInputNumber,
  ElTag,
  ElDivider,
  ElMessageBox,
  ElImage
} from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { LeeInputNumber } from '@/components/LeeInputNumber'
import TagEdit from './TagEdit.vue'

import { useIcon } from '@/hooks/web/useIcon'
const iconAdd = useIcon({ icon: 'ep:plus' })
const iconDel = useIcon({ icon: 'ep:delete' })

const props = defineProps({
  // modelValue: propTypes.any.def('')
  skuList: {
    type: [Object, String],
    default: () => {}
  },
  goodsSku: {
    type: [Array, String],
    default: () => []
  }
})

watch(
  () => props.skuList,
  (val: any) => {
    if (val === unref(sku_list)) return
    sku_list.value = val
  }
)

watch(
  () => props.goodsSku,
  (val: any) => {
    if (val === unref(goods_sku)) return
    goods_sku.value = val
    // 初始化一次
    onSetSku()
  }
)

const dialogVisible = ref(false)

const dialogTitle = ref('')

// const sku_list = ref<any>(props.skuList)
const sku_list = ref<any>(props.skuList)

// `goods_sku_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
// `goods_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '商品ID',
// `goods_sku_specs` text COLLATE utf8mb4_unicode_ci COMMENT '商品规格（JSON）',
// `goods_stock` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '商品库存',
// `goods_price` decimal(10,2) DEFAULT NULL COMMENT '商品价格',
// const tableData = ref<any>(props.goodsSku)
const goods_sku = ref<any>(props.goodsSku)
// const InputRef = ref()

const delTag = (keyIndex, tagIndex) => {
  sku_list.value[keyIndex].tag.splice(tagIndex, 1)
}
var thisKeyIndex: number
var thisTagIndex: number

const TagEditRef = ref<ComponentRef<typeof TagEdit>>()
const actionType = ref('')
const tagData = ref({})
const action = async (type: string, data: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'addKey':
      ElMessageBox.prompt('', '添加规格组', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
        .then(async ({ value }) => {
          sku_list.value.push({
            name: value,
            tag: []
          })
        })
        .catch(() => {})
      break
    case 'delKey':
      ElMessageBox.confirm('确定删除这个规格组？', '删除规格组', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
        .then(async () => {
          sku_list.value.splice(data.keyIndex, 1)
        })
        .catch(() => {})
      break
    case 'editTag':
      dialogTitle.value = '编辑标签'
      // 给编辑页面赋值
      thisKeyIndex = data.keyIndex
      thisTagIndex = data.tagIndex
      tagData.value = sku_list.value[data.keyIndex].tag[data.tagIndex]
      dialogVisible.value = true
      break
    case 'addTag':
      dialogTitle.value = '添加标签'
      // 给编辑页面赋值
      thisKeyIndex = data.keyIndex
      thisTagIndex = data.tagIndex
      tagData.value = {}
      dialogVisible.value = true
      break
    default:
      console.log('未知类型', type)
  }
}

const save = async () => {
  const TagEdit = unref(TagEditRef)
  switch (actionType.value) {
    case 'editTag':
      await TagEdit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const formData = (await TagEdit?.getFormData()) as any
          sku_list.value[thisKeyIndex].tag[thisTagIndex] = {
            ...sku_list.value[thisKeyIndex].tag[thisTagIndex],
            ...formData
          }
          dialogVisible.value = false
        }
      })
      break
    case 'addTag':
      await TagEdit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const formData = (await TagEdit?.getFormData()) as any
          // 这里需要知道新增的是那个规格组
          sku_list.value[thisKeyIndex].tag.push({ ...formData, clicked: false, disabled: true })
          dialogVisible.value = false
        }
      })
      break
    default:
      console.log('未知类型', actionType.value)
  }
}

// 设置SKU
const onSetSku = () => {
  let newAttr = addAttr(sku_list.value) //遍历出所有属性
  // 属性和已有数据结合
  let newData: any = []
  newAttr.forEach((item: any) => {
    let name = item.join('，')
    let aaa = goods_sku.value.find(function (tItem) {
      return tItem.goods_sku_specs == name
    })
    if (aaa) {
      newData.push(aaa)
    } else {
      newData.push({ goods_sku_specs: name, goods_stock: 0, goods_price: 0 })
    }
  })
  goods_sku.value = newData
}

// 遍历出所有属性
function addAttr(array, data = []) {
  if (array != null) {
    array.forEach((item) => {
      data = forma_array(item.tag, data)
    })
    function forma_array(array1, data) {
      let rows: any = []
      if (data.length == 0) {
        if (array1) {
          array1.forEach((item) => {
            if (item.name) {
              rows.push([item.name])
            } else {
              rows.push([])
            }
          })
        }
      } else {
        data.forEach((item) => {
          array1.forEach((item1) => {
            if (item1.name) {
              rows.push([...item, item1.name])
            } else {
              rows.push([...item])
            }
          })
        })
      }
      return rows
    }
  }
  return data
}

const getData = () => {
  return {
    sku_list: sku_list.value ? JSON.parse(JSON.stringify(sku_list.value)) : {},
    goods_sku: goods_sku.value ? JSON.parse(JSON.stringify(goods_sku.value)) : []
  }
}

defineExpose({
  getData
})
</script>

<template>
  <div>
    <ContentWrap title="设置规格">
      <div class="mb-10px">
        <div class="mb-10px">
          <ElButton type="primary" :icon="iconAdd" @click="action('addKey')">添加规格组</ElButton>
          <ElButton type="success" :icon="iconAdd" @click="onSetSku()">格式化SKU</ElButton>
        </div>
        <div v-for="(item, keyIndex) in sku_list" :key="keyIndex" style="line-height: 34px">
          <el-divider v-if="keyIndex != 0" style="margin: 10px 0 7px" />
          <span class="tag-group__title m-1 line-height-2">
            <!-- {{ item }}{{ Object.keys(item)[0] }} -->
            {{ item.name }}：
          </span>
          <el-tag
            v-for="(tag, tagIndex) in item.tag"
            :key="'key_' + keyIndex + '_tag_' + tagIndex"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="delTag(keyIndex, tagIndex)"
            size="large"
            :effect="tag.clicked == false ? 'light' : 'dark'"
            @dblclick="action('editTag', { keyIndex, tagIndex })"
          >
            <el-image
              v-if="tag.imgUrl"
              style="width: 25px; height: 25px; vertical-align: middle; margin-right: 5px"
              :src="tag.imgUrl"
              fit="fill"
            />
            <span
              style="
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
              "
            >
              {{ tag.name }}
            </span>
          </el-tag>

          <el-button
            type="primary"
            class="button-new-tag ml-1"
            :icon="iconAdd"
            @click="action('addTag', { keyIndex })"
          >
            添加标签
          </el-button>
          <el-button
            type="danger"
            class="button-new-tag ml-1"
            :icon="iconDel"
            @click="action('delKey', { keyIndex })"
          >
            删除标签组
          </el-button>
        </div>
        <!-- <ElTable :data="tableData" style="width: 100%" :show-header="false">
            <ElTableColumn prop="sku" label="SKU" width="180" />
            <ElTableColumn prop="name" label="Name" width="180" />
          </ElTable> -->
      </div>
    </ContentWrap>
    <ContentWrap title="SKU">
      <el-table :data="goods_sku">
        <el-table-column prop="goods_sku_specs" label="规格（SKU）" />
        <el-table-column prop="goods_stock" label="商品库存">
          <template #default="scope">
            <LeeInputNumber v-model="scope.row.goods_stock" />
          </template>
        </el-table-column>
        <el-table-column prop="goods_price" label="商品价格">
          <template #default="scope">
            <LeeInputNumber v-model="scope.row.goods_price" :precision="2" />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="address" label="Address" /> -->
      </el-table>
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" :max-height="250">
      <TagEdit ref="TagEditRef" :data="tagData" />
      <template #footer>
        <ElButton type="primary" @click="save()"> 提交 </ElButton>
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
  </div>
</template>
